<template>
  <dialog-editor ref="dialog" :print-func='printHandle' :top='top' :col-flag-func="true" :printWhenSubmit="true"></dialog-editor>
</template>

<script>
import DialogEditor from '@/components/DialogEditor'
import dialogMixins from '@/utils/commonDialogMixins'
import {mRequest, mRequestPromise} from '@/utils/request'

export default {
  mixins: [dialogMixins],
  components: {DialogEditor},
  data() {
    return {
      dataFormConfig: {
        id: {
          hidden: true
        },
        contractType: {
          hidden: true,
          default: 1
        },
        clientName: {
          label: '客户',
          showInMultiMode: true,
          default: '散户'
        },
        contractTime: {
          label: '订单时间',
          type: 'date',
          showInMultiMode: true,
          changedCallback: this.contractTimeChangedHandler,
          placeholder: '请选择出库时间'
        },

  /*      clientType:{
          label: '客户类型',
          type: 'radio',
          showInMultiMode: true,
          radioList: [
            {label: 0, text: '公司客户'},
            {label: 1, text: '个人'},
            {label: 3, text: '散户'},
          ],
          default: 1
        },*/
        contractNo: {
          label: '订单编号-自动',
          showInMultiMode: true,
          disabled: true,
        },
        // productIdLightBottle: {
        //   label: '光瓶',
        //   type: 'list',
        //   list: [],
        //   placeholder: '请输入订单',
        //   filterable: true,
        //   selectCallback: this.orderSelectCallback
        // },
        productId: {
          hidden: true,
          label: '产品',
          type: 'list',
          list: [],
          //   disabled: true,
          filterable: true,
          clearable: true,
          placeholder: '请输入产品',
          selectCallback: this.productSelectCallback
        },
        productWeight: {
          label: '克数',
          type: 'number',
          max: 1000,
          default: 0
        },

        realSaleNumber: {
          label: '数量合计',
          showInMultiMode: true,
          disable: true,
          type: 'number',
          max: 100000000
        },
        discountPrice: {
          label: '优惠金额',
          showInMultiMode: true,
          type: 'number',
          selectCallback: this.contractTotalPriceSet,
          max: 1000000
        },
        paymentWay:{
          label: '付款方式',
          type: 'radio',
          showInMultiMode: true,
          radioList: [
            {label: 0, text: '已付全款'},
            {label: 1, text: '已付定金'},
            {label: 90, text: '未付款'},
          ],
          default: 0
        },
        totalAmount: {
          label: '合计总价',
          showInMultiMode: true,
          disabled: true,
          type: 'number',
          max: 100000000
        },

        productBatchNoQueueId:{
          label: '批号',
          hidden: true,

          type: 'list',
          list: [],
          filterable: true,
          clearable: true,
          placeholder: '请输入产品',
        },
        orderStatus: {
          label: '订单状态',
          type: 'radio',
          showInMultiMode: true,
          radioList: [
            {label: 0, text: '配货中'},
            {label: -1, text: '缺货'},
            {label: 50, text: '部分发货'},
            {label: 55, text: '已全出货'},
            {label: 99, text: '客户取消'}
          ],
          default: 55
        },
        vouchAccount: {
          label: '收款账户',
          type: 'list',
          list: [],
          showInMultiMode: true,
          //   disabled: true,
          filterable: true,
          clearable: true,
          default: 2
        },
        paymentTotalAmount:{
          label: '付款金额',
          showInMultiMode: true,
          type: 'number',
          max: 100000000,
          default: 0
        },
        // deliverType: {
        //   label: '付费方式',
        //   type: 'radio',
        //   showInMultiMode: true,
        //   radioBorder: true,
        //   radioList: [
        //     {text: '支付宝', label: '支付宝'},
        //     {text: '微信', label: '微信'},
        //   ],
        //   default: '支付宝'
        // },
        remark: {
          label: '备注',
          inputType: 'textarea',
          showInMultiMode: true,
          placeholder: '请输入备注'
        },
      },
      orderListFilterByClientId: [],
      orderList: [],
      top: '7vh',
      multiAddProduct: false
    }
  },
  methods: {
    async contractTimeChangedHandler(date) {
      const res = await mRequestPromise('contractApi/contractNoGetByContractTime', {contractTime: date})
      const contractNo = this.R.path(['data', 'contractNo'], res)

      if (!contractNo) {
        return
      }
      //  const deliveryTime = moment(date).add(45, 'days').format('YYYY-MM-DD');

      this.dataForm.contractNo = contractNo
      //   this.dataForm.deliveryTime = deliveryTime
    },
    printHandle(params) {
      this.$vBus.$emit('SHOW_PRINT_DIALOG', (win) => {
        const tmpDocument = this.R.prop('document', win)
        const content = tmpDocument.querySelector('#content')
        const {clientId, tableData} = params

        const outTime = this.R.propOr('', 'outTime', params)
        const tickerNo = this.R.propOr('', 'tickerNo', params)

        if (this.R.isNil(tmpDocument) || this.R.isNil(content) || !(tableData instanceof Array) || tableData.length < 0) {
          tmpDocument.body.innerHTML = '信息不全'
          return
        }
        const addTd = (tr, str) => {
          const td = tmpDocument.createElement('td')

          td.innerText = str
          tr.appendChild(td)
        }

        tmpDocument.querySelector('#time').innerHTML = outTime.toString().substr(0, 11)
        tmpDocument.querySelector('#tickerNo').innerHTML = tickerNo.toString()

        content.innerHTML = ''

        const client = this.R.find(this.R.propEq('id', clientId), this.dataFormConfig.clientId.list)
        const clientName = client.name

        tableData.forEach(row => {
          const {
            productId,
            productWeight,
            boxSupplyWay,
            boxNumber,
            boxZhiNumber,
            trayNumber,
            trayEachZhiNumber,
            trayLayerNumber,
            weightCount,
            realSaleNumber,
            remark
          } = row
          const product = this.R.find(this.R.propEq('id', productId), this.dataFormConfig.productId.list)

          const productName = product.name
          const boxSupplyWayName = boxSupplyWay === 0 ? '纸箱' : boxSupplyWay === 1 ? '托盘' : '自供'

          const tr = tmpDocument.createElement('tr')

          addTd(tr, clientName)
          // addTd(tr, orderName)
          addTd(tr, productName)
          addTd(tr, boxSupplyWayName)
          if (boxSupplyWay === 0) {
            addTd(tr, boxZhiNumber)
            addTd(tr, boxNumber)
          } else if (boxSupplyWay === 1) {
            addTd(tr, trayEachZhiNumber * trayLayerNumber)
            addTd(tr, trayNumber)
          } else {
            addTd(tr, '')
            addTd(tr, '')
          }
          addTd(tr, weightCount)
          addTd(tr, productWeight)
          //addTd(tr, saleNumber)
          addTd(tr, realSaleNumber)
          //    addTd(tr, outTime)
          addTd(tr, remark)
          content.appendChild(tr)
        })

      }, true)
    },
    productSelectHandle(productId, cb) {
      if (this.R.isNil(productId) || this.R.isEmpty(productId)) {
        return
      }
      mRequest('productApi/productInfoInfo', {id: productId}, ({data}) => {
        if (!(cb instanceof Function)) {
          return
        }
        return cb(data)
      })
    },
    orderSelectHandle(orderId, cb) {
      if (this.R.isNil(orderId) || this.R.isEmpty(orderId)) {
        return
      }
      mRequest('orderApi/orderDetailInfo', {id: orderId}, ({data}) => {
        if (!(cb instanceof Function)) {
          return
        }
        return cb(data)
      })
    },
    orderSelectCallback() {
      this.orderSelectHandle(this.dataForm.orderDetailId, (data) => {
        this.dataForm['productId'] = this.R.pathOr(0, ['orderDetail', 'productId'], data)
        this.dataForm['productWeight'] = this.R.pathOr(0, ['orderDetail', 'productWeight'], data)
        this.dataForm['boxSupplyWay'] = this.R.pathOr(0, ['orderDetail', 'boxSupplyWay'], data)
        this.dataForm['boxZhiNumber'] = this.R.pathOr(0, ['orderDetail', 'boxZhiNumber'], data)
        //TODO 加一个入库数量的提示

      })
    },
    addNewClientInfo() {
      const cb = (newValue) => {
        this.initClientInfoList()
        this.dataForm.clientId = newValue.id
      }
      this.$parent.openClientInfoDialog(cb)

    },
    allOrderListGet() {
      mRequest('orderApi/getOrderDetailList', {clientId: this.dataForm.clientId}, ({data}) => {
        this.orderList = this.R.propOr([], 'list', data)
      })
    },
    clientIdSelectCallback() {
      if (this.multiAddProduct) {
        mRequest('orderApi/getOrderDetailListBtyClientId', {clientId: this.dataForm.clientId}, ({data}) => {
          this.orderListFilterByClientId = this.R.propOr([], 'list', data)
        })
      }else {
        mRequest('orderApi/getOrderDetailListByClientId', {clientId: this.dataForm.clientId}, ({data}) => {
          this.dataFormConfig['orderDetailId'].list = this.R.propOr([], 'list', data)
        })
      }
    },
    productSelectCallback(value) {
      mRequest('productApi/productInfoInfo', {id: value}, (res) => {
        const productInfo = this.R.path(['data', 'productInfo'], res)
        this.dataForm['productWeight'] = productInfo['productWeight']
      })
    },
    numberChanged() {
      const packType = this.R.propOr(0, 'boxSupplyWay', this.dataForm)
      const productWeight = this.R.propOr(0, 'productWeight', this.dataForm)

      if (packType === 0) {
        const boxNumber = this.R.propOr(0, 'boxNumber', this.dataForm)
        const boxZhiNumber = this.R.propOr(0, 'boxZhiNumber', this.dataForm)
        const scrapNumber = this.R.propOr(0, 'scrapNumber', this.dataForm)

        this.dataForm.realSaleNumber = boxNumber * boxZhiNumber + scrapNumber
      } else if (packType === 1) {
        const trayLayerNumber = this.R.propOr(0, 'trayLayerNumber', this.dataForm)
        const trayEachZhiNumber = this.R.propOr(0, 'trayEachZhiNumber', this.dataForm)
        const trayNumber = this.R.propOr(0, 'trayNumber', this.dataForm)
        const scrapNumber = this.R.propOr(0, 'scrapNumber', this.dataForm)

        this.dataForm.countProductNumber = trayLayerNumber * trayEachZhiNumber * trayNumber + scrapNumber
        this.dataForm.realSaleNumber = trayLayerNumber * trayEachZhiNumber * trayNumber  + scrapNumber
      }
      this.dataForm.weightCount = (this.dataForm.realSaleNumber * productWeight)/100000
    },
    contractTotalPriceSet() {

      let _tableData = this.$refs.dialog.$refs.editTableView.$refs.xTable.tableData

      const orderPriceList = _tableData.map(window.R.propOr(0, 'totalPrice'))
      const orderProductNumberList = _tableData.map(window.R.propOr(0, 'orderProductNumber'))
      const freight = this.R.propOr(0, 'freight', this.dataForm)
      const discountPrice = this.R.propOr(0, 'discountPrice', this.dataForm)

      this.dataForm.totalAmount =Math.round( (window.R.reduce(window.R.add, 0, orderPriceList) - discountPrice + freight)*100)/100
      this.dataForm.realSaleNumber = window.R.reduce(window.R.add, 0, orderProductNumberList)
      if (this.dataForm.paymentMethod == 0) {
        this.dataForm.paymentTotalAmount = this.dataForm.totalAmount
      }
    },

    productBatchNoSelectHandle(productId, cb) {
      if (this.R.isNil(productId) || this.R.isEmpty(productId)) {
        return
      }
      mRequest('productApi/getProductBatchNoQueueList', {'productId': productId}, ({data}) => {
        const productBatchNoQueueList =  this.R.propOr([], 'list', data)
        if (productBatchNoQueueList) {
          let messageStr = ''
          productBatchNoQueueList.forEach(item=>{
              messageStr += '批号:' + item.name + ',剩余数量:' + item.countNumber + '</br>'
            }
          )
          this.$message({
            message: messageStr,
            type: 'primary',
            duration: 3000,
            dangerouslyUseHTMLString: true,
            onClose: () => {}
          })
          return cb(data)
        }
      })
    },
    init(id, multiAdd) {
      this.dataForm.id = id || 0
      this.initProductInfoList()
      this.initFinanceAccountInfoList('vouchAccount')
      this.initProductBatchNoQueueList('productBatchNoQueueId')

      /*      this.initOrderDetailList()*/
      //    this.initClientInfoList('clientId')
      /*      this.initBoxInfoIdList('boxId')*/
      /* this.initTrayList()
       this.allOrderListGet()*/
      this.multiAddProduct = multiAdd
      const props = {
        dataForm: this.dataForm,
        config: this.dataFormConfig,
        dataRule: this.getNeedDataRule( 'status'),
        initApi: 'contractApi/contractOrderInfoInfo',
        saveApi: 'contractApi/contractAndOrderSave',
        updateApi: 'contractApi/updateContractAndOrder',
        objectName: 'contractOrderInfo'
      }

      if (multiAdd) {
        props['multiSaveApi'] = 'contractApi/contractAndOrderSave'
        props['editTableConfig'] = {
          productId: {
            title: '产品',
            editRenderName: 'xVueBoxSearch',
            optionsGet: () => {
              return this.dataFormConfig.productId.list.map(item => ({label: item.name, value: item.id}))
            },
            valueChangeEvent: (row) => {
              const {productId} = row

              this.productSelectHandle(productId, data => {
                row.productWeight = this.R.pathOr(0, ['productInfo', 'productWeight'], data)
                row.unitPrice = this.R.pathOr(0, ['productInfo', 'unitPrice'], data)
                row.countNumber = this.R.pathOr(0, ['productInfo', 'countNumber'], data)
                row.historyUnitPrice = this.R.pathOr(0, ['productInfo', 'historyUnitPrice'], data)
              })
              this.productBatchNoSelectHandle(productId, data => {
                if (data.list) {
                  row.productBatchNoQueueId=data.list[0].id
                }
              })
            }
          },
          boxZhiNumber:{
            title: '箱只',
            type: 'number',
            default: 0,
            valueChangeEvent: (row) => {
              weightChangedHandle(row)
            }
          },
          boxNumber:{
            title: '箱数',
            type: 'number',
            default: 0,
            valueChangeEvent: (row) => {
              weightChangedHandle(row)
            }
          },
          orderProductNumber: {
            title: '总数量',
            type: 'number',
            default: 0,
            valueChangeEvent: (row) => {
              weightChangedHandle(row)
            }
          },
          unitPrice: {
            title: '单价',
            default: 0,
            valueChangeEvent: (row) => {
              weightChangedHandle(row)
            }
          },

          totalPrice: {
            title: '总价',
            default: 0
          },
          productBatchNoQueueId: {
            title: '批号',
            width:170,
            editRenderName: 'xVueBoxSearch',
            optionsGet: () => {
              return this.dataFormConfig.productBatchNoQueueId.list.map(item => ({label: item.name, value: item.id}))
            }
          },
          purchaseType: {
            title: '货源采购',
            type: 'select',
            default: 0,
            optionsGet: () => {
              return [
                {label: '现货', value: 0},
                {label: '普采', value: 1},
                {label: '特采', value: 2}
              ]
            }
          },
          purchaseNumber: {
            title: '采购数量',
            type: 'number',
            default: 0,
          },
          productWeight: {
            title: '克数',
            default: 0
          },
          historyUnitPrice: {
            title: '历史价格'
          },
          countNumber: {
            title: '库存数量',
            type: 'number',
            default: 0
          },
          remark: {
            title: '备注',
            type: 'String'
          }
        }
      }

      const weightChangedHandle = (row) => {
        const boxNumber = this.R.propOr(0, 'boxNumber',row)
        const boxZhiNumber = this.R.propOr(0, 'boxZhiNumber', row)
        const unitPrice = this.R.propOr(0, 'unitPrice', row)
        if(boxNumber!=0||boxZhiNumber!=0) {
          const orderProductNumber = boxZhiNumber * boxNumber
          row['totalPrice'] = Math.round(unitPrice * orderProductNumber* 100)/100;
          row['orderProductNumber'] = orderProductNumber
          row['remark'] = boxZhiNumber+'只*' + boxNumber+'件'
        }else {
            const orderProductNumber = this.R.propOr(0, 'orderProductNumber', row)
          row['totalPrice'] = Math.round(unitPrice * orderProductNumber * 100) / 100
        }

        this.contractTotalPriceSet()

      }
      this.$refs.dialog.initDialog(props)

      this.$nextTick(() => {
        const dataForm = this.dataForm

        // Object.defineProperty(dataForm, 'totalAmount', {
        //   get() {
        //     return dataForm['realSaleNumber'] * dataForm['productWeight']
        //   }
        // })
      })
    }
  }
}
</script>
<style scoped>
/deep/ .el-form-item {
  margin-bottom: 12px;
}
</style>
